<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Category;
use App\Models\Shop\Product;

class ProductController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_category' => 'on',
        ]);
    }

    /**
     * 商城前端---分类页
     */
    public function category()
    {
        $categories = Category::get_categories();
        return view('wechat.product.category', compact('categories'));
    }

    /**
     * 商城前端---商品列表
     */
    public function index(Request $request)
    {
        //搜索商品
        $where = function ($query) use ($request) {
            if ($request->has('category_id') and $request->category_id != '') {
                $category_id = $request->category_id;
                $product_ids = \DB::table('category_product')->where('category_id', $category_id)->pluck('product_id');
                $query->whereIn('id', $product_ids);
            }
        };
        $products = Product::where($where)->get();
        return view('wechat.product.index', compact('products'));
    }

    /**
     * 显示商品详情
     */
    public function show(Request $request)
    {
        $product = Product::with('product_galleries')->find($request->id);
        $recommends = Product::where('is_recommend', 1)
            ->orderBy('sort_order', 'desc')
            ->get();
        return view('wechat.product.show', compact('product', 'recommends'));
    }

    /**
     * 搜索商品
     */
    function search()
    {
        $products = Product::where('is_recommend', true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->get();
        return view('wechat.product.search', compact('products'));
    }

}
